package cAmqp

import (
	"github.com/gin-gonic/gin"
	"github.com/rabbitmq/amqp091-go"

	"gitee.com/csingo/cLog"
)

func Produce(ctx *gin.Context, option ProduceOption) (err error) {
	var channel *amqp091.Channel
	var driver *AmqpConf_Driver
	var name string

	self.plock.Lock()
	defer self.plock.Unlock()

	name, channel, driver, err = self.channel(ctx, option.DriverName, option.DriverConf, ConnectionType_Producer)
	if err != nil {
		cLog.WithContext(ctx, map[string]any{
			"source": "cAmqp.Produce",
			"option": option,
			"err":    err.Error(),
		}).Error("cAmqp.Produce:获取channel异常")
		return
	}
	defer func() {
		self.close(ctx, driver.Connection, name)
	}()

	err = channel.ExchangeDeclare(
		driver.ExchangeName,
		string(driver.ExchangeType),
		option.Exchange.Durable,
		// option.Exchange.AutoDeleted,
		false,
		option.Exchange.Internal,
		option.Exchange.NoWait,
		option.Exchange.Arguments,
	)
	if err != nil {
		return
	}

	if !option.OnlyPush {
		_, err = channel.QueueDeclare(
			driver.QueueName,
			option.Queue.Durable,
			// option.Queue.AutoDeleted,
			false,
			option.Queue.Exclusive,
			option.Queue.NoWait,
			option.Queue.Arguments,
		)
		if err != nil {
			return
		}

		err = channel.QueueBind(driver.QueueName, driver.RoutingKey, driver.ExchangeName, option.Bind.NoWait, option.Bind.Arguments)
		if err != nil {
			return
		}
	}

	err = channel.PublishWithContext(
		ctx,
		driver.ExchangeName,
		driver.RoutingKey,
		option.Mandatory,
		option.Immediate,
		option.Message,
	)
	if err != nil {
		return
	}

	return
}
